package com.bstek.uflo.form.command;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

import org.hibernate.jdbc.Work;

import com.bstek.uflo.command.Command;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.form.model.TableDefinition;
import com.bstek.uflo.form.view.table.dialect.Dialect;

/**
 * @author Jacky.gao
 * @since 2013年11月8日
 */
public class GenerateTablesCommand implements Command<Object> {
	public TableDefinition table;
	public GenerateTablesCommand(TableDefinition table){
		this.table=table;
	}
	public Object execute(Context context) {
		final Collection<Dialect> dialects=context.getApplicationContext().getBeansOfType(Dialect.class).values();
		context.getSession().doWork(new Work(){
			public void execute(Connection connection) throws SQLException {
				buildTable(table,connection,dialects);
			}
		});
		return null;
	}
	private void buildTable(TableDefinition t,Connection connection,Collection<Dialect> dialects) throws SQLException {
		Statement stmt=connection.createStatement();
		try{
			String[] createSql=null;
			for(Dialect dialect:dialects){
				if(dialect.support(connection)){
					createSql=dialect.generateCreateTableSchema(t);
					break;
				}
			}
			if(createSql==null){
				throw new IllegalArgumentException("No match dbdialect.");
			}
			for(String sql:createSql){
				stmt.executeUpdate(sql);				
			}
		}finally{
			stmt.close();
		}
	}
}
